package com.mengniu.commerce.sync.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mengniu.commerce.common.core.config.RestTemplateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 13754
 */
@Component
@Slf4j
public class RestTemplateUtil {

   @Resource
   RestTemplateConfig restTemplateConfig;

   @Resource
   private InsertMnApiLogModelUtil insertMnApiLogModelUtil;

    public static final String baseURL = "https://t-openapi-gateway.mengniu.cn/";
    public static final String clientId = "7b420980-9efd-4d4b-8209-809efd4d4b99";
    public static final String secret = "83BA7A00-3025-4A5A-BA7A-0030252A5A03";

    public String buildSign(Long time){
        String md5 =encryptStringToMD5(clientId + secret + time).toUpperCase();
        return md5;
    }

    public  String encryptStringToMD5(String input) {
        try {
            // 创建一个MD5消息摘要对象
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 计算MD5哈希值
            byte[] inputBytes = input.getBytes();
            byte[] hashBytes = md.digest(inputBytes);

            // 将字节数组转换为十六进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : hashBytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();

        } catch (NoSuchAlgorithmException e) {
            // 处理异常
            e.printStackTrace();
            return null;
        }
    }
    /***
     * 向三方发起请求（json形式）
     * @param
     * @param
     * ***/
    public JSONObject doPost(JSONObject args, String uri) {
        long startTime = System.currentTimeMillis();
        try {
            long currentTimeMillis = System.currentTimeMillis();
            ClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
            requestHeaders.set("sign",buildSign(currentTimeMillis));
            requestHeaders.set("clientID",clientId);
            requestHeaders.set("t",currentTimeMillis+"");
            HttpEntity<String> requestEntity = new HttpEntity<>(args.toJSONString(), requestHeaders);
            ResponseEntity<String> responseResult = restTemplateConfig.restTemplate(factory).exchange(uri, HttpMethod.POST, requestEntity, String.class);
            long endTime = System.currentTimeMillis();
            String res = responseResult.getBody();
            insertMnApiLogModelUtil.insert(args.toJSONString(),res,uri,null,JSONObject.parseObject(res).getString("requestId"));
            log.info("\r\n请求三方：" + uri + "，\n参数：\n" + args + "\n返回结果：\n" + JSON.toJSONString(res) + ", 三方请求耗时:" + (endTime - startTime));
            if (res != null) {
                return JSONObject.parseObject(res);
            }
        } catch (Exception e) {
            log.error("向第三方平台提交数据出错" + "\nURL:" + uri + "\n参数：" + args + ":" + e);
        }
        return null;
    }

    public JSONObject constant(JSONObject param,String operationUnitType,String apiVersion){
        param.put("operationUnitType",operationUnitType);
        param.put("apiVersion",apiVersion);
        return param;
    }


}
